import allure
import cv2


def allure_equal_assert(label, expect_result, test_result):
    """
    :param label: expect result description
    :param expect_result:
    :param test_result:
    :return:
    """
    with allure.step(f"Validation - Label:'{label}' - Expect Result:{expect_result} - Test Result:{test_result}"):
        assert expect_result == test_result, (
            f"Validation Error - Label:'{label}' - Expect Result:{expect_result} - Test Result:{test_result}")


def assert_images_equal(img_path1: str, img_path2: str):
    # 读取两张图片
    img1 = cv2.imread(img_path1)
    img2 = cv2.imread(img_path2)

    # 先检查尺寸和通道数
    if img1 is None or img2 is None:
        raise AssertionError("有图片读取失败，请检查路径")

    if img1.shape != img2.shape:
        raise AssertionError(f"图片尺寸或通道不同：{img1.shape} != {img2.shape}")

    # 做像素差：完全相同的话，差值图应该全是 0
    diff = cv2.subtract(img1, img2)
    b, g, r = cv2.split(diff)
    if cv2.countNonZero(b) != 0 or cv2.countNonZero(g) != 0 or cv2.countNonZero(r) != 0:
        # 标红并保存差异图，方便查看哪里不一样
        diff_abs = cv2.absdiff(img1, img2)
        gray = cv2.cvtColor(diff_abs, cv2.COLOR_BGR2GRAY)
        _, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
        red_img = img1.copy()
        red_img[mask != 0] = (0, 0, 255)
        diff_path = "diff_marked.png"
        cv2.imwrite(diff_path, red_img)
        raise AssertionError(f"两张图片像素不一致，差异图已保存到: {diff_path}")


if __name__ == '__main__':
    p1 = r'F:\WorkSpace\pycharam_workspace\pu_cn_ui_auto\data\after.jpg'
    p2 = r'F:\WorkSpace\pycharam_workspace\pu_cn_ui_auto\data\before.jpg'
    assert_images_equal(p1,p2)